import Mocha from './mocha';
import CheckFocusAccount from './check_focus_account';

const getMochaConfig = () => {
    return new Promise((resolve, reject) => {
        Mocha.getConfig()
            .then((cfg) => {
                resolve(cfg.link_list);
            })
            .catch((err) => {
                reject(err);
            });
    });
};

let count = 0;
const filterNotFocusAccounts = () => {
    return new Promise((resolve, reject) => {
        let resArr = [];
        getMochaConfig()
            .then((beforeLinkList) => {
                Object.keys(beforeLinkList).forEach((itemKey) => {
                    formatData(beforeLinkList[`${itemKey}`]).then((indexs) => {
                        resArr.push({
                            [`${itemKey}`]: {
                                origin: beforeLinkList[`${itemKey}`],
                                after: indexs
                            }
                        });
                        if (Object.keys(beforeLinkList).length === resArr.length) {
                            let list = {};
                            for (var key in resArr) {
                                list[`${Object.keys(resArr[key])[0]}` ] = resArr[key][`${Object.keys(resArr[key])[0]}`];
                            }
                            console.log('------过滤后未关注的公号列表------',list);
                            resolve(list);
                        }
                    });
                });
            })
            .catch((err) => {
                count += 1;
                if (count < 3) {
                    filterNotFocusAccounts();
                    return;
                } else {
                    reject(err);
                }
            });
    });
};

const formatData = (arr) => {
    let appidList = arr.map((itemVal) => {
        return itemVal.appid;
    });
    let unFocusAccountArray = [];
    return new Promise((resolve, reject) => {
        CheckFocusAccount.request(
            'GET',
            `${getApp().mox.user.unionid}?appid=${appidList.join(',')}`
        )
            .then((res) => {
                arr.forEach((oItem, oIndex) => {
                    const index = res.findIndex((nItem) => oItem.appid === nItem.appid);
                    if (index >= 0) {
                        const resIndex = res[index].status === 0 ? oIndex : -1;
                        if (resIndex >= 0) unFocusAccountArray.push(resIndex);
                    } else {
                        unFocusAccountArray.push(oIndex);
                    }
                });
                resolve(unFocusAccountArray);
            })
            .catch((err) => {
                reject(err);
            });
    });
};
export { filterNotFocusAccounts };
